package com.leo.filter;

import com.leo.util.HttpUtil;
import com.leo.wapper.MyRequestWrapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: MyFilter
 * @Description: 自定义过滤器
 * @Author: leo825
 * @Date: 2020-02-03 17:21
 * @Version: 1.0
 */


public class MyFilter implements Filter {

    //日志
    private static final Logger LOGGER = LogManager.getLogger();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("MyFilter过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取HttpServletRequest对象
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String ipAddr = HttpUtil.getIpAddr(httpServletRequest);
        LOGGER.info("ip地址为：" + ipAddr);
        Map paramMap = new HashMap<>();
        paramMap.put("ipAddr", ipAddr);
        MyRequestWrapper myRequestWrapper = new MyRequestWrapper(httpServletRequest, paramMap);
        chain.doFilter(myRequestWrapper, response);
    }

    @Override
    public void destroy() {
        LOGGER.info("MyFilter过滤器被销毁");
    }
}
